<template>
    <div><!--面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!--卡片试图-->
<el-card class="box-card">
  <!--搜索服务区-->
  <el-row :gutter="20">
  <el-col :span="4">
    <el-input placeholder="请输入内容" v-model="querfont.query" clearable @clear="getUserList">
    <el-button slot="append" icon="el-icon-search" @click="getUserList">
    </el-button>
  </el-input>
</el-col>
  <el-col :span="4"><el-button type="primary" @click="addUser= true">添加用户</el-button></el-col>
</el-row>
<!--用户列表区域-->
<el-table border stripe
      :data="userlist">
      <el-table-column
      type="index">
      </el-table-column>
      <el-table-column
        prop="username"
        label="姓名">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话">
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色">
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="状态">
        <!--scope属性当前状态栏信息.row-->
        <template slot-scope="scope">
           <el-switch
            v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
      </el-switch>
     </template>
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="操作" width="208px">
        <template slot-scope="scope">
          <!--修改按钮-->
          <el-tooltip content="修改" placement="top">
          <el-button type="primary" icon="el-icon-edit" size="min" @click="showEditDialog(scope.row.id)"></el-button>
          </el-tooltip>
          <!--删除按钮-->
          <el-tooltip content="删除" placement="top" >
          <el-button type="danger" icon="el-icon-delete" size="min" @click="RemoveUserById(scope.row.id)"></el-button>
          </el-tooltip>
          <!--分配权限按钮-->
          <el-tooltip content="用户权限" placement="top">
          <el-button type="warning" icon="el-icon-setting" size="min"></el-button>
        </el-tooltip>
      </template>
      </el-table-column>
    </el-table>
    <!--页码-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="querfont.pagenum"
      :page-sizes="[1, 2, 5,10 ]"
      :page-size="querfont.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
</el-card>
<!--添加用户对话框-->
<el-dialog
  title="添加用户"
  :visible.sync="addUser"
  width="30%" @close="addDialogClosed">
  <!--主体 ref引用名称-->
  <el-form :model="addForm" :rules=" addFormrules" ref="addfontref" label-width="70px">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="addForm.password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
  <el-form-item label="电话" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <!--底部-->
  <span slot="footer" class="dialog-footer">
    <el-button @click="addUser= false">取 消</el-button>
    <el-button type="primary" @click="AddUser">确 定</el-button>
  </span>
</el-dialog>
<!--修改用户信息-->
<el-dialog
  title="修改用户"
  :visible.sync="editDialogVisble"
  width="30%" @close="editDialogClosed">
  <!--主体 ref引用名称-->
  <el-form :model="editform" :rules=" addFormrules" ref="editfontref" label-width="70px">
  <el-form-item label="用户名" prop="username" >
    <el-input v-model="editform.username" disabled></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="editform.email"></el-input>
  </el-form-item>
  <el-form-item label="电话" prop="mobile">
    <el-input v-model="editform.mobile"></el-input>
  </el-form-item>
  </el-form>
  <!--底部-->
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisble= false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
</el-dialog>
    </div>
</template>
<script>
export default ({
  //  当前组件所有数据
  data () {
    // 验证邮箱规则
    // const checkEmail = (rules, value, cb) => {
    //   const regEmali =  /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/
    //   if (regEmali.test(value)) {
    //     return cb()
    //   }
    //   cb(new Error('请再次输入密码'))
    // }
    // //  验证手机号规则
    // const checkphone = (rules, value, cb) => {
    //   const regphone = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
    //   if (regphone.test(value)) {
    //     return cb()
    //   }
    //   cb(new Error('请输入正确的手机号'))
    // }
    // 生命周期存放
    return {
    //  获取用户列表的参数对象
      querfont: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      addUser: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 控制修改对话框
      editDialogVisble: false,
      editform: {
        username: '',
        email: '',
        mobile: ''
      },
      addFormrules: {
        username: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 10,
          message: '用户名的长度在3-10个字符之间'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 6,
          max: 15,
          message: '密码的长度在6-15个字符之间'
        }],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        },
        {
          min: 6,
          max: 15,
          message: '密码的长度在6-15个字符之间'
        }],
        mobile: [{
          required: true,
          message: '请输入电话',
          trigger: 'blur'
        },
        {
          min: 6,
          max: 15,
          message: '密码的长度在6-15个字符之间'
        }]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.querfont })
      if (res.meta.status !== 200) { return this.$message.error('获取失败') }
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    handleSizeChange (newSize) {
      //  console.log(newSize)
      this.querfont.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.querfont.pagenum = newPage
      this.getUserList()
    },
    async userStateChanged (userinfont) {
      //  this.$http.put('users/:uId/state/:type')
      const { data: res } = await this.$http.put(`users/${userinfont.id}/state/${userinfont.mg_state}`)
      if (res.mg_state !== 200) {
        this.userinfont.mg_state = !userinfont.mg_state
        return this.$message.error('更新错误')
      }
      return this.$message.success('更新成功')
    },
    //  根据id删除用户
    async RemoveUserById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户删除则返回值为cancel
      // 如果用户确认则返回字符 confirm
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功！')
      this.getUserList()
    },
    addDialogClosed () {
      this.$refs.addfontref.resetFields()
    },
    AddUser () {
      this.$refs.addfontref.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.addUser = false
        this.getUserList()
      })
    },
    // 展示编辑对话框
    editDialogClosed () {
      this.$refs.editfontref.resetFields()
    },
    editUserInfo () {
      this.$refs.editfontref.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户请求
        const { data: res } = await this.$http.put('users/' + this.editform.id, { email: this.editform.email, mobile: this.editform.mobile })
        if (res.meta.status !== 200) {
          this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.editDialogVisble = false
        this.getUserList()
      })
    },
    async showEditDialog (id) {
      // 可以发起修改用户请求
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('查询失败')
      }
      this.$message.success('查询成功')
      this.editform = res.data
      this.editDialogVisble = true
    }
  }
})
</script>
<style lang="less" scoped>
.el-card{
    margin-top: 15px;
    font-size: 12px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
</style>
